package net.takela.push.service.sp.impl;

import net.takela.common.spring.exception.ParamException;
import net.takela.common.spring.http.HttpResponse;
import net.takela.common.utils.StringUtils;
import net.takela.push.model.PushApp;
import net.takela.push.model.PushMsgTpl;
import net.takela.push.service.sp.ServiceProvider;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Created by baboy on 18/10/2017.
 */
@Service("emailPushService")
public class EmailServiceProvider extends ServiceProvider {
    @Override
    public HttpResponse<?> send(String msgCode, Map<String, String> data, String ip) {
        PushMsgTpl msgTpl = getMsgTpl(msgCode);
        Map conf = msgTpl.getConf();
        Map dataMap = new HashMap();
        if(conf.containsKey("data")){
            dataMap.putAll( (Map)conf.get("data") );
        }
        dataMap.putAll(data);

        for (String k :  (Set<String>) dataMap.keySet()){
            Object ov = dataMap.get(k);
            String v = "";
            if(ov != null){
                v = StringUtils.formatPlaceholders(ov.toString(), dataMap);
            }
            dataMap.put(k, v);
        }
        String to = (String)dataMap.get("email");
        String subject = (String)dataMap.get("subject");
        String content = (String)dataMap.get("content");

        if (org.apache.commons.lang3.StringUtils.isEmpty(to)){
            throw new ParamException("param.error.desc","email");
        }
        boolean ret = send(to,subject,content);
        if (ret){
            return HttpResponse.success();
        }else{
            return HttpResponse.error();
        }

    }
    public boolean send(String to, String subject, String content){

        final Properties props = new Properties();
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        final Map<String,Object> conf = (Map<String, Object>)getPushApp().getConf();
        for (String k : conf.keySet()){
            Object v =conf.get(k);
            if(v instanceof String){
                props.setProperty(k, (String)v);
            }
        }

        try {
            Authenticator authenticator = new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.auth");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            //使用JavaMail发送邮件的5个步骤
            //1、创建session
            Session session = Session.getInstance(props, authenticator);
            //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
            session.setDebug(true);
            //2、通过session得到transport对象
//            Transport ts = session.getTransport();
            //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和能够正常发送邮件给收件人。

            //ts.connect("smtp.sohu.com", "gacl", "邮箱密码");
            //4、创建邮件
            String from = props.getProperty("from");
            Message message = createTextMail(from,to, subject,content,session);
            //5、发送邮件
            Transport.send(message, message.getAllRecipients());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static MimeMessage createTextMail(String from, String to, String title, String content, Session session) throws Exception {
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(from));
        //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
        String a[] = to.split(",");
        for (String t : a){
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(t));
        }
        //邮件的标题
        message.setSubject(title);
        //邮件的文本内容
        message.setContent(content, "text/html;charset=UTF-8");
        //返回创建好的邮件对象
        return message;
    }
}
